<template>
  <div class="cart-container">
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <span class="header-title">
          <i class="el-icon-shopping-cart-2"></i>
          我的购物车
        </span>
        <el-button 
          type="danger" 
          size="small" 
          plain
          icon="el-icon-delete"
          @click="handleClearCart"
          :disabled="cartList.length === 0">
          清空购物车
        </el-button>
      </div>

      <!-- 购物车列表 -->
      <el-table
        ref="cartTable"
        :data="cartList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: '600' }">
        <el-table-column
          type="selection"
          width="55"
          align="center">
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="300">
          <template slot-scope="scope">
            <div class="product-info-cell">
              <div class="product-images">
                <img 
                  v-for="(img, index) in getImages(scope.row.productImages)" 
                  :key="index"
                  :src="img" 
                  :alt="scope.row.productName"
                  :style="{ zIndex: getImages(scope.row.productImages).length - index }"
                  class="product-img">
              </div>
              <div class="product-details">
                <div class="product-name" @click="viewProductDetail(scope.row.productId)">
                  {{ scope.row.productName }}
                </div>
                <div class="product-meta">
                  <el-tag size="mini" type="success">{{ scope.row.categoryName }}</el-tag>
                  <el-tag size="mini" type="info" v-if="scope.row.productBrand">{{ scope.row.productBrand }}</el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价" min-width="120" align="center">
          <template slot-scope="scope">
            <div class="price-cell">
              <span class="price-symbol">¥</span>
              <span class="price-value">{{ scope.row.productPrice }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="数量" min-width="150" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="999"
              size="small"
              @change="handleQuantityChange(scope.row)">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="小计" min-width="120" align="center">
          <template slot-scope="scope">
            <div class="subtotal-cell">
              <span class="subtotal-symbol">¥</span>
              <span class="subtotal-value">{{ calculateSubtotal(scope.row) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="cartList.length === 0" description="购物车是空的，快去挑选商品吧">
        <el-button type="primary" @click="goToProductList">去购物</el-button>
      </el-empty>

      <!-- 底部结算栏 -->
      <div class="cart-footer" v-if="cartList.length > 0">
        <div class="footer-left">
          <el-checkbox 
            v-model="selectAll" 
            @change="handleSelectAll">
            全选
          </el-checkbox>
          <el-button 
            type="text" 
            @click="handleBatchDelete"
            :disabled="selectedItems.length === 0">
            删除选中
          </el-button>
        </div>
        
        <div class="footer-right">
          <div class="total-info">
            <span class="total-label">已选商品</span>
            <span class="total-count">{{ selectedItems.length }}</span>
            <span class="total-label">件，合计：</span>
            <span class="total-price">
              <span class="price-symbol">¥</span>
              <span class="price-value">{{ totalPrice }}</span>
            </span>
          </div>
          <el-button 
            type="primary" 
            size="large"
            :disabled="selectedItems.length === 0"
            @click="handleCheckout">
            去结算
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 结算弹窗 -->
    <el-dialog
      title="确认订单"
      :visible.sync="checkoutDialogVisible"
      width="700px"
      :close-on-click-modal="false">
      <div class="checkout-content">
        <!-- 收货信息 -->
        <div class="section">
          <div class="section-title">收货信息</div>
          <el-form :model="checkoutForm" label-width="100px">
            <el-form-item label="收货人">
              <el-input v-model="checkoutForm.receiverName" placeholder="请输入收货人姓名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="checkoutForm.receiverPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <el-input 
                type="textarea" 
                v-model="checkoutForm.receiverAddress" 
                :rows="3"
                placeholder="请输入详细收货地址">
              </el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 商品列表 -->
        <div class="section">
          <div class="section-title">商品清单</div>
          <div class="order-items">
            <div class="order-item" v-for="item in selectedItems" :key="item.id">
              <img :src="getFirstImage(item.productImages)" :alt="item.productName">
              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-spec">{{ item.categoryName }}</div>
              </div>
              <div class="item-price">¥{{ item.productPrice }} × {{ item.quantity }}</div>
              <div class="item-total">¥{{ calculateSubtotal(item) }}</div>
            </div>
          </div>
        </div>

        <!-- 订单金额 -->
        <div class="section">
          <div class="order-summary">
            <div class="summary-row">
              <span>商品金额</span>
              <span class="summary-value">¥{{ totalPrice }}</span>
            </div>
            <div class="summary-row">
              <span>运费</span>
              <span class="summary-value">¥0.00</span>
            </div>
            <div class="summary-row total-row">
              <span>订单总额</span>
              <span class="summary-total">¥{{ totalPrice }}</span>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="checkoutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePlaceOrder">提交订单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCartList, updateCartQuantity, deleteCartItem, batchDeleteCartItems, clearCart } from '@/api/cart';
import { createOrder } from '@/api/order';

export default {
  name: 'UserCart',
  data() {
    return {
      cartList: [],
      selectedItems: [],
      selectAll: false,
      loading: false,
      checkoutDialogVisible: false,
      checkoutForm: {
        receiverName: '',
        receiverPhone: '',
        receiverAddress: ''
      }
    };
  },
  computed: {
    // 计算总价
    totalPrice() {
      return this.selectedItems.reduce((total, item) => {
        return total + (parseFloat(item.productPrice) * item.quantity);
      }, 0).toFixed(2);
    }
  },
  created() {
    this.loadCartList();
  },
  methods: {
    // 加载购物车列表
    async loadCartList() {
      this.loading = true;
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
          this.$router.push('/login');
          return;
        }
        
        const response = await getCartList(userInfo.id);
        if (response.data.success) {
          this.cartList = response.data.data || [];
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载购物车失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载购物车失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 获取图片列表（最多显示3张）
    getImages(images) {
      if (!images) {
        return ['https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'];
      }
      const imageArray = images.split(',').filter(img => img.trim());
      return imageArray.slice(0, 3);
    },
    
    // 获取第一张图片
    getFirstImage(images) {
      if (!images) {
        return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
      }
      const imageArray = images.split(',').filter(img => img.trim());
      return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    },
    
    // 计算小计
    calculateSubtotal(row) {
      return (parseFloat(row.productPrice) * row.quantity).toFixed(2);
    },
    
    // 选择变化
    handleSelectionChange(selection) {
      this.selectedItems = selection;
      this.selectAll = selection.length === this.cartList.length && this.cartList.length > 0;
    },
    
    // 全选
    handleSelectAll(val) {
      if (val) {
        this.cartList.forEach(row => {
          this.$refs.cartTable.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.cartTable.clearSelection();
      }
    },
    
    // 修改数量
    async handleQuantityChange(row) {
      try {
        const response = await updateCartQuantity(row.id, row.quantity);
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: '数量已更新',
            type: 'success',
            duration: 2000
          });
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '更新失败',
            type: 'error',
            duration: 2000
          });
          this.loadCartList();
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '更新失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
        this.loadCartList();
      }
    },
    
    // 删除单项
    async handleDelete(row) {
      this.$confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const response = await deleteCartItem(row.id, userInfo.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            });
            this.loadCartList();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '删除失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '删除失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    // 批量删除
    async handleBatchDelete() {
      if (this.selectedItems.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择要删除的商品',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedItems.length} 个商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const ids = this.selectedItems.map(item => item.id);
          const response = await batchDeleteCartItems(ids, userInfo.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            });
            this.loadCartList();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '删除失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '删除失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    // 清空购物车
    async handleClearCart() {
      this.$confirm('确定要清空购物车吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          const response = await clearCart(userInfo.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '购物车已清空',
              type: 'success',
              duration: 2000
            });
            this.loadCartList();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '清空失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '清空失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    // 去结算
    handleCheckout() {
      if (this.selectedItems.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择要购买的商品',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      // 重置表单
      this.checkoutForm = {
        receiverName: '',
        receiverPhone: '',
        receiverAddress: ''
      };
      
      this.checkoutDialogVisible = true;
    },
    
    // 提交订单
    async handlePlaceOrder() {
      // 验证表单
      if (!this.checkoutForm.receiverName) {
        this.$notify({
          title: '提示',
          message: '请输入收货人姓名',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.checkoutForm.receiverPhone) {
        this.$notify({
          title: '提示',
          message: '请输入联系电话',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.checkoutForm.receiverAddress) {
        this.$notify({
          title: '提示',
          message: '请输入收货地址',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        
        // 构造订单详情
        const orderDetails = this.selectedItems.map(item => ({
          productId: item.productId,
          productName: item.productName,
          productImage: this.getFirstImage(item.productImages),
          price: item.productPrice,
          quantity: item.quantity
        }));
        
        // 获取购物车ID列表
        const cartIds = this.selectedItems.map(item => item.id);
        
        // 创建订单
        const orderData = {
          userId: userInfo.id,
          totalAmount: this.totalPrice,
          receiverName: this.checkoutForm.receiverName,
          receiverPhone: this.checkoutForm.receiverPhone,
          receiverAddress: this.checkoutForm.receiverAddress,
          orderDetails: orderDetails,
          cartIds: cartIds
        };
        
        const response = await createOrder(orderData);
        
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: '订单提交成功',
            type: 'success',
            duration: 2000
          });
          
          this.checkoutDialogVisible = false;
          
          // 跳转到我的订单页面
          this.$router.push('/user/order-list');
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '订单提交失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '订单提交失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 查看商品详情
    viewProductDetail(productId) {
      this.$router.push(`/user/product-detail/${productId}`);
    },
    
    // 去购物
    goToProductList() {
      this.$router.push('/user/product-list');
    }
  }
};
</script>

<style scoped>
.cart-container {
  min-height: calc(100vh - 130px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  font-size: 20px;
  margin-right: 8px;
  color: #2c5f2d;
}

/* 商品信息单元格 */
.product-info-cell {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-images {
  position: relative;
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.product-img {
  position: absolute;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.product-img:nth-child(1) {
  left: 0;
  top: 0;
}

.product-img:nth-child(2) {
  left: 15px;
  top: 5px;
}

.product-img:nth-child(3) {
  left: 30px;
  top: 10px;
}

.product-images:hover .product-img {
  transform: translateX(-5px);
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  cursor: pointer;
  transition: color 0.3s;
}

.product-name:hover {
  color: #2c5f2d;
}

.product-meta {
  display: flex;
  gap: 8px;
}

/* 价格单元格 */
.price-cell,
.subtotal-cell {
  display: flex;
  align-items: baseline;
  justify-content: center;
}

.price-symbol,
.subtotal-symbol {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 600;
}

.price-value,
.subtotal-value {
  font-size: 18px;
  color: #f56c6c;
  font-weight: 700;
  margin-left: 2px;
}

/* 底部结算栏 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  margin-top: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.total-label {
  font-size: 14px;
  color: #606266;
}

.total-count {
  font-size: 18px;
  font-weight: 600;
  color: #2c5f2d;
}

.total-price {
  display: flex;
  align-items: baseline;
  margin-left: 10px;
}

.total-price .price-symbol {
  font-size: 18px;
  color: #f56c6c;
  font-weight: 700;
}

.total-price .price-value {
  font-size: 28px;
  color: #f56c6c;
  font-weight: 700;
  margin-left: 4px;
}

/* 结算弹窗 */
.checkout-content {
  max-height: 600px;
  overflow-y: auto;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #2c5f2d;
}

/* 订单商品 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.order-item img {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.item-spec {
  font-size: 13px;
  color: #909399;
}

.item-price,
.item-total {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.item-total {
  font-weight: 600;
  color: #f56c6c;
  min-width: 80px;
  text-align: right;
}

/* 订单汇总 */
.order-summary {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.total-row {
  padding-top: 15px;
  border-top: 2px solid #dcdfe6;
  font-size: 16px;
  font-weight: 600;
}

.summary-total {
  font-size: 24px;
  font-weight: 700;
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-footer {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .footer-right {
    flex-direction: column;
    gap: 15px;
  }

  .order-item {
    flex-wrap: wrap;
  }
}
</style>

